package com.yifeng.repo.base.utils.servlet;

import com.gomcarter.frameworks.base.json.JsonData;
import com.gomcarter.frameworks.base.json.JsonError;
import com.yifeng.repo.base.utils.converter.JacksonHelper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Created by zyh on 2024/03/15.
 */
public class ResponseHelper {

    public static void doWrite(HttpServletResponse resp, Object obj) throws IOException {
        JsonData jsonData = new JsonData(obj);
        resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
        resp.setContentType("application/json");
        resp.setHeader("Cache-Control", "no-cache");
        resp.getOutputStream().write(JacksonHelper.toJson(jsonData).getBytes(StandardCharsets.UTF_8));
    }

    public static void doError(HttpServletResponse resp, int code, String msg) throws IOException {
        JsonError jsonError = new JsonError(msg, code);
        resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
        resp.setContentType("application/json");
        resp.setHeader("Cache-Control", "no-cache");
        resp.getOutputStream().write(JacksonHelper.toJson(jsonError).getBytes(StandardCharsets.UTF_8));
    }

    /**
     * @deprecated 业务代码不要修改 http status
     */
    public static void doError(HttpServletResponse resp, int respStatus, int code, String msg) throws IOException {
        JsonError jsonError = new JsonError(msg, code);
        resp.setStatus(respStatus);
        resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
        resp.setContentType("application/json");
        resp.setHeader("Cache-Control", "no-cache");
        resp.getOutputStream().write(JacksonHelper.toJson(jsonError).getBytes(StandardCharsets.UTF_8));
    }
}
